<template>
  <div class="register-container">
    <el-card class="register-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <h1 class="title">加入剧本杀管理系统</h1>
          <p class="subtitle">创建您的管理员账户</p>
        </div>
      </template>

      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="rules"
        @submit.prevent="handleRegister"
        size="large"
      >
        <el-form-item prop="username">
          <el-input
            v-model="registerForm.username"
            placeholder="请输入用户名"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item prop="email">
          <el-input
            v-model="registerForm.email"
            type="email"
            placeholder="请输入邮箱地址"
            :prefix-icon="Message"
            clearable
          />
        </el-form-item>

        <el-form-item prop="realName">
          <el-input
            v-model="registerForm.realName"
            placeholder="请输入真实姓名"
            :prefix-icon="User"
            clearable
          />
        </el-form-item>

        <el-form-item prop="phone">
          <el-input
            v-model="registerForm.phone"
            placeholder="请输入手机号"
            :prefix-icon="Iphone"
            clearable
          />
        </el-form-item>

        <el-form-item prop="roleId" label-width="0">
          <el-select
            v-model="registerForm.roleId"
            placeholder="请选择角色类型"
            :prefix-icon="Avatar"
            style="width: 100%"
          >
            <el-option label="游客" :value="4" />
            <el-option label="发行商" :value="2" />
            <el-option label="店铺" :value="3" />
          </el-select>
        </el-form-item>

        <!-- 店铺角色提示 -->
        <el-alert
          v-if="showShopTip"
          title="温馨提示"
          type="warning"
          :closable="false"
          show-icon
          style="margin-bottom: 18px"
        >
          <template #default>
            <p style="margin: 0; font-size: 14px;">
              您正在注册店铺账号，注册后需要补充店铺信息并等待审核通过后才能购买剧本。
            </p>
          </template>
        </el-alert>

        <el-form-item prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            :prefix-icon="Lock"
            show-password
            clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="handleRegister"
            :loading="loading"
            class="register-btn"
            size="large"
          >
            {{ loading ? '注册中...' : '注册' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="footer">
        <el-text type="info" size="small">
          已有账户？
          <router-link to="/login" class="login-link">立即登录</router-link>
        </el-text>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { type FormInstance, type FormRules } from 'element-plus'
import { User, Lock, Message, Iphone, Avatar } from '@element-plus/icons-vue'
import { registerAPI } from '@/api/user'
const router = useRouter()
const route = useRoute()

const registerFormRef = ref<FormInstance>()
const loading = ref(false)
const showShopTip = ref(false) // 是否显示店铺提示

const registerForm = reactive({
  username: '',
  email: '',
  realName: '',
  phone: '',
  password: '',
  roleId: 4, // 默认注册为用户
})

// 检查路由参数，如果是从商城跳转来的，预选店铺角色
onMounted(() => {
  if (route.query.role === 'shop') {
    registerForm.roleId = 3
    showShopTip.value = true
    ElMessage.info('请完成注册并选择店铺角色')
  }
})

const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符', trigger: 'blur' },
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符', trigger: 'blur' },
  ],
  realName: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  phone: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
  roleId: [{ required: true, message: '请选择角色类型', trigger: 'change' }],
})

const handleRegister = async () => {
  if (!registerFormRef.value) return

  await registerFormRef.value.validate((valid) => {
    if (valid) {
      submitRegister()
    }
  })
}

const submitRegister = async () => {
  loading.value = true

  try {
    // 这里添加实际的注册逻辑
    // 模拟注册请求
    const { data: res } = await registerAPI({
      ...registerForm,
      id: 0 // 注册时 id 为 0，由后端生成
    })
    console.log(res)
    if (res.code !== 1) {
      ElMessage.error(res.msg || '注册失败！')
      return
    }

    // 根据角色类型决定跳转页面
    if (registerForm.roleId === 3) {
      // 店铺角色，提示需要补充店铺信息
      ElMessage.success('注册成功！请登录后完善店铺信息')
      router.push('/login')
    } else {
      // 其他角色，直接跳转到登录页
      ElMessage.success(res.msg || '注册成功！请登录您的账户')
      router.push('/login')
    }
  } catch (error: unknown) {
    const errorMsg = (error as { msg?: string })?.msg || '注册失败，请稍后重试'
    ElMessage.error(errorMsg)
  } finally {
    loading.value = false
  }
}
</script>

<style scoped>
.register-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
  padding: 1rem;
}

.register-card {
  width: 100%;
  max-width: 450px;
}

.card-header {
  text-align: center;
}

.title {
  font-size: 1.5rem;
  font-weight: 500;
  color: #333;
  margin: 0 0 0.5rem 0;
}

.subtitle {
  font-size: 0.875rem;
  color: #666;
  margin: 0;
}

.register-btn {
  width: 100%;
}

.footer {
  text-align: center;
  margin-top: 1rem;
}

.login-link {
  color: #409eff;
  text-decoration: none;
  margin-left: 0.25rem;
}

.login-link:hover {
  text-decoration: underline;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .register-container {
    padding: 0.75rem;
  }

  .register-card {
    max-width: 100%;
  }

  .title {
    font-size: 1.25rem;
  }
}

@media (max-width: 480px) {
  .register-container {
    padding: 0.5rem;
  }

  .title {
    font-size: 1.125rem;
  }
}
</style>
